package com.example.wacoffee_user.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class simpleRedisLock implements  ILock{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public simpleRedisLock(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        String name = Thread.currentThread().getName();
        Boolean success= stringRedisTemplate.opsForValue().setIfAbsent("lock:"+CurrentHoler.getCurrentId(),name,timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        stringRedisTemplate.delete("lock:"+CurrentHoler.getCurrentId());
    }
}
